/*
 * Copyright (C) 2013 rothens
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package rpg.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author rothens
 */
public class Preferences {

    private static Preferences instance;
    private static String fileName = "prefs.dat";
    private HashMap<String, String> prefs = new HashMap<String, String>();

    private Preferences() {
        generateDefaults();
        load();
    }

    public static Preferences getInstance() {
        if (instance == null) {
            instance = new Preferences();
        }
        return instance;
    }

    private void generateDefaults() {
        prefs.put("charName", "");
        if (!new File(fileName).exists()) {
            save();
        }
    }

    private synchronized void load() {
        LineReader lr = new LineReader(new File(fileName));
        while (lr.hasNext()) {
            String line = lr.next();
            String[] split = line.split("=");
            String key = split[0], val = (split.length > 1 && !split[1].equalsIgnoreCase("null")) ? split[1] : null;
            System.out.println(key + "-" + val);
            prefs.put(key, val);
        }
    }

    private synchronized void save() {

        PrintWriter pw = null;
        try {
            File f = new File(fileName);
            pw = new PrintWriter(f);
            for (String s : prefs.keySet()) {
                Object val = prefs.get(s);
                pw.println(String.format("%s=%s", s, (val == null) ? "" : val.toString()));
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Preferences.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            pw.close();
        }
    }

    public String getValue(String key) {
        return prefs.get(key);
    }

    public void setValue(String key, String value) {
        prefs.put(key, value);
        save();
    }
}
